package org.redis.cluster.transport.netty.processor;

import org.redis.cluster.transport.netty.server.NettyServerSession;
import org.redis.cluster.transport.session.Session;
import org.redis.cluster.transport.session.SessionContext;
import org.redis.cluster.transport.session.SessionProcessor;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class NettyHandler extends SimpleChannelInboundHandler<Object> {
	
	private SessionProcessor processor;
	private SessionContext context;
	
	public NettyHandler(SessionProcessor processor,SessionContext context) {
		this.processor=processor;
		this.context=context;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
		Session session=getSession(ctx);
		processor.process(session, msg);
	}
	
	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		Session session=getSession(ctx);
		processor.created(session);
	}
	
	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		Session session=getSession(ctx);
		processor.closed(session);
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		Session session=getSession(ctx);
		processor.exception(session, cause);
	}
	
	protected Session getSession(ChannelHandlerContext ctx) {
		return new NettyServerSession(ctx,context);
	}
}